/********************************************************************
 * Copyright(c) 2023-2023 Grayson Zheng.
 * File: bit.h
 * Description: Data reading program for DHT11 temperature and
 * humidity sensor module based on 89C51/89C52 design.
 * Version: 1.0
 * Date: 2023-08-27
 * Author: zhengxinyu13@qq.com
 * ---------- Revision History ----------
 * <version>
 * <date>
 * <author>
 * <desc>
 * Modified to be suitable to the new coding rules in all functions.
 ********************************************************************/

#include "dht11.h"

void DHT11_start()
{
	SET_BIT(DHT11_DATA);
	RESET_BIT(DHT11_DATA);
	delay_xms(20);
	SET_BIT(DHT11_DATA);
	delay_40us();
	while (DHT11_DATA);
	while (!DHT11_DATA);
	while (DHT11_DATA);
}

void read_DHT11_data(uint_8 *DHT11_data, uint_8 len)
{
	uint_8 i, j, temp, flag;

	DHT11_start();

	for (i = 0; i < len; i++) {
		for (j = 0; j < CHAR_LENGTH; j++) {
			while (!DHT11_DATA);
			delay_40us();
			if (DHT11_DATA) {
				SET_BIT(flag);
				while (DHT11_DATA);
			} else {
				RESET_BIT(flag);
			}
			temp <<= 1;
			temp |= flag;
		}
		DHT11_data[i] = temp;
	}
}

uint_8 check_DHT11_data(uint_8 *DHT11_data, uint_8 len)
{
	uint_8 sum = 0;
	uint_8 i;

	for (i = 0; i < len - 1; i++)
		sum += DHT11_data[i];

	if (sum == DHT11_data[len - 1])
		return 1;
	else
		return 0;
}
